package com.tarena.sentinel.demo01.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MyRulesDataSource implements InitFunc {
    //如果sentinel加载了自定义数据源 init方法就是读取规则的逻辑方法
    //读取flowRules.json文件形成规则对象
    @Override
    public void init() throws Exception {
        //1. 拿到文件路径
        URL resource = MyRulesDataSource.class.getClassLoader().getResource("flowRules.json");
        String filePath=resource.getPath();
        System.out.println("当前文件路径:"+filePath);
        //2. 读取交给sentinel转化成flowRules对象
        FileRefreshableDataSource dataSource=
                new FileRefreshableDataSource(filePath, new Converter() {
                    //方法参数就是文件内容实际是字符串
                    //方法返回值就是转化的List规则对象
                    @Override
                    public Object convert(Object o) {
                        String json=(String)o;
                        System.out.println("读取到文件内容:"+json);
                        List<FlowRule> flowRules = JSON.parseArray(json, FlowRule.class);
                        return flowRules;
                    }
                });
        FlowRuleManager.register2Property(dataSource.getProperty());
        System.out.println("自定义数据源加载完毕");
    }
}
